package com.itqf.controller;

import cn.dsna.util.images.ValidateCode;
import com.itqf.dto.LoginUser;
import com.itqf.entity.SysUser;
import com.itqf.utils.R;
import com.itqf.utils.ShiroUtils;
import com.itqf.utils.SysConstant;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/10/19
 * @Time: 下午4:43
 */
@RestController
public class SysUserController {

    @RequestMapping("/captcha.jpg")
    public  void  captcha(HttpServletResponse response){
        try {
            ValidateCode code = new ValidateCode(60,20,1,5);
            String text = code.getCode();
            //shiro+redis
            ShiroUtils.setAttribute(SysConstant.KAPTCHA,text);

            ImageIO.write(code.getBuffImg(),"jpg",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @RequestMapping("/sys/login")
    //@RequestBody   前端 1）json字符串  JSON.stringify({});2）Content-Type="application/json"

    //不用 @RequestBody,直接对象接值    前端 json对象  {}或者表单数据

    //public R  login(@RequestBody SysUser sysUser){
    public R  login(@RequestBody LoginUser sysUser){
        String code = (String) ShiroUtils.getAttribute(SysConstant.KAPTCHA);
        if (!code.equalsIgnoreCase(sysUser.getCaptcha())){
            return R.error("验证码错误");
        }

        //1,用户名密码封装成UsernamePasswordToken
        UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUsername()
                ,sysUser.getPassword());
        if (sysUser.isRememberMe()){
            token.setRememberMe(true);
        }


        //2,Subject对象
        Subject subject = SecurityUtils.getSubject();
        //3.登录   内部查找 Realm    认证方法
        subject.login(token);

        return R.ok("登录成功");
    }


    @RequestMapping("/sys/user/info")
    public  R info(){
        //  {}  [{},{}]  {{menuList:[{},{}]}}
        //session
        Subject subject = SecurityUtils.getSubject();
        //因为在自定义realm中  返回SimpleAuthenticationInfo中存储用户信息
        SysUser user = (SysUser) subject.getPrincipal();
        //	vm.user = r.user;
        return  R.ok().put("user",user);

    }

    @RequestMapping("/sys/user/logout")
    public  R  loginout(){
        //清空session，取消用户登录（认证）状态
        SecurityUtils.getSubject().logout();

        return  R.ok();
    }





}
